package com.example.tellwin.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.example.tellwin.MainApplication;
import com.example.tellwin.R;
import com.example.tellwin.api.TwjfApi;
import com.example.tellwin.base.BaseDialog;
import com.example.tellwin.base.DaggerRxComponent;
import com.example.tellwin.common.Common;
import com.example.tellwin.event.ExpenseCalendarEvent;
import com.example.tellwin.event.ShareEvent;
import com.example.tellwin.utils.CommonUtils;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import javax.inject.Inject;

/**
 * @author : LinZePeng
 * @date : 2020/11/16
 * @Describe ：
 **/
public class ShareDialog extends BaseDialog implements ShareContract.View {


    private TextView wechatTv;
    private TextView pengyouquanTv;
    private TextView cancelTv;
    private IWXAPI api;

    private int type;
    private String id;
    private String content;
    private String url = "http://tellwinedu.com/tianwen-";

    private String active = "active/?id=";
    private String question = "share/?id=";
    private String order = "orderDetail/?id=";
    private String invitation = "invitation/?id=";

    @Inject
    SharePresenter mPresenter;

    public ShareDialog(@NonNull Context context, int type, String id, String content) {//1是活动 2是问题 3订单
        super(context, R.style.ActionSheetDialogStyle);
        this.type = type;
        this.id = id;
        this.id = id;
        this.content = content;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_share);
        Window window = this.getWindow();
        //设置位置在屏幕底部
        window.setGravity(Gravity.BOTTOM);
        //设置弹入弹出动画
        window.setWindowAnimations(R.style.BottomDialog_Animation);
        //设置为全屏dialog
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(params);
        initView();
        initEvent();
        intiData();
        api = WXAPIFactory.createWXAPI(getContext(), Common.WeChatPayId, false);
        api.registerApp(Common.WeChatPayId);
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        EventBus.getDefault().unregister(this);
    }

    private void initView() {
        DaggerRxComponent.builder()
                .baseAppComponent(MainApplication.getAppComponent())
                .build()
                .inject(this);
        mPresenter.attachView(this);

        wechatTv = (TextView) findViewById(R.id.wechat_tv);
        pengyouquanTv = (TextView) findViewById(R.id.pengyouquan_tv);
        cancelTv = (TextView) findViewById(R.id.cancel_tv);
    }

    private void initEvent() {
        cancelTv.setOnClickListener(v -> this.dismiss());
        wechatTv.setOnClickListener(v -> {
            share(SendMessageToWX.Req.WXSceneSession);
        });
        pengyouquanTv.setOnClickListener(v -> {
            share(SendMessageToWX.Req.WXSceneTimeline);
        });
    }

    private void share(int mTargetScene) {

        WXWebpageObject webpage = new WXWebpageObject();
        if (type == 1) {
            webpage.webpageUrl = url + active + id;
        } else if (type == 2) {
            webpage.webpageUrl = url + question + id;
        } else if (type == 3) {
            webpage.webpageUrl = url + order + id;
        } else if (type == 4) {
            webpage.webpageUrl = url + invitation + id;
        }

        //用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = getContext().getResources().getString(R.string.app_name);
        msg.description = content;
        Bitmap thumbBmp = BitmapFactory.decodeResource(getContext().getResources(), R.mipmap.app_icon);
        msg.thumbData = CommonUtils.bmpToByteArray(thumbBmp, true);

        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = mTargetScene;
        req.userOpenId = "";

        //调用api接口，发送数据到微信
        api.sendReq(req);
    }

    private void sendShareHttp() {
        String shareType = "";
        if (type == 1) {
            shareType = "3";
        } else if (type == 2) {
            shareType = "1";
        } else if (type == 3) {
            shareType = "2";
        } else if (type == 4) {
            //  webpage.webpageUrl = url +invitation + id;
            return;
        }
        mPresenter.share(shareType, id);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    private void intiData() {
    }

    @Subscribe
    public void onEvent(ShareEvent event) {
        if (event.isSuccess) {
            sendShareHttp();
        }
        dismiss();
    }

    @Override
    public void share() {

    }

    @Override
    public void onLoading() {

    }

    @Override
    public void complete() {

    }

    @Override
    public void showError() {

    }

    @Override
    public void showToast(String msg) {

    }
}
